<template>
    <view class="flex-start-center item-box" v-for="item in PropsData.data" :key="item.c_guid" @click="handleFileAction(item)">
        <view class="left">
            <span class="point" v-show="item.c_read_count === 0 && item.c_download_count === 0"></span>

            <image :src="'../../../static/img/knowledge/' +item.c_docimg_url" mode="scaleToFill" class="image" />
        </view>
        <view class="right flex-column-between">
            <view class="text-ellipsis sub_title flex_1">{{item.c_title}}</view>
            <view class="flex-start-center">
                <eui-tag 
                    :text="item.c_cname" 
                    :bgColor="themeBgColor"
                    :color="themeColor"
					:borderColor="themeBgColor"
                ></eui-tag>
                <view class="text-ellipsis sub_des">{{ item.c_mk_dt }}</view>
                <view class="text-ellipsis sub_des">{{ item.c_mk_username }}</view>
            </view>
        </view>
    </view>
    <view v-if="PropsData.data.length == 0" class="no-data">
        <image src="@/static/img/no_data.png" mode="aspectFit" class="image" />
    </view>
</template>
  
<script setup lang="ts">
import service from '@/common/service';
import eventBus from '@/pages/MainViews/eventBus';
import { ref, defineProps } from 'vue';
import { useLoginStore } from '@/store/modules/useLoginStore';
import { useMainStore } from '@/store/modules/store';
import { useThemeStore } from '@/store/themeStore';
const LoginStore = useLoginStore();
const mainStore = useMainStore();
const themeStore = useThemeStore(); // 主题
const themeBgColor = ref(themeStore.theme == 'theme-blue' ? 'rgba(224, 239, 255, 0.5)' : 'rgba(255, 239, 224, 0.5)')
const themeColor = ref(themeStore.theme == 'theme-blue' ? '#02B7E6' : '#FF6430')
/**
 *  知识门户
 */

 interface File {
    c_docimg_url: string,
    c_title: string,
    c_mk_dt: string,
    c_mk_username: string,
    c_download_count: number,
    c_cname: string,
    c_guid: string,
    c_type?: string;
    c_file_name: string;
    filePath: string;
    [key: string]: any;
 }

 const PropsData = defineProps<{ data: Array<File> }>();


const downloadFile = (file: File) => {
    console.log(file);
	
    uni.downloadFile({
        url: file.filePath, // PDF文件的网络地址
        success: function(res) {
            if (res.statusCode === 200) {
                uni.saveFile({
                    tempFilePath: res.tempFilePath,
                    success: function(saveRes) {
                        console.log('文件保存成功，路径为：' + saveRes.savedFilePath);
                        uni.showToast({
                            title: '保存成功',
                            icon: 'success',
                            mask: true
                        })
                        setTimeout(() => {
                            let fileExtension = file.c_file_name.substring(file.c_file_name.lastIndexOf('.') + 1);
                            uni.openDocument({
                                filePath: saveRes.savedFilePath, // 文件路径
                                fileType: fileExtension, // 文件类型
                                showMenu: true,
                                success: function() {
                                    console.log('文件预览成功');
                                },
                                fail: function(err) {
                                    console.error('文件预览失败：', err);
                                }
                            });
                        }, 2000);
                    },
                    fail: function(err) {
                        console.error('文件保存失败：', err);
                        uni.showToast({
                            title: '文件保存失败：'+ err,
                            icon: 'error',
                            mask: true
                        })
                    }
                });
            } else {
                service.enjoyShowToast('下载文件失败，状态码：' + res.statusCode)
                console.error('下载文件失败，状态码：' + res.statusCode);
            }
        },
        fail: function(err) {
            service.enjoyShowToast('下载文件请求失败：' + err)
        }
    });
}
//文件已存在
const FileExistsCallback = (entry, options, filename, guid) => {
    uni.showModal({
        title: '提示',
        content: '选择的文件已下载过,是否直接打开',
        success: function (res) {
            if (res.confirm) {
                // 直接打开
                plus.runtime.openFile(options.filename, function (e) {
                    uni.showToast({
                        duration: 3500,
                        icon: 'none',
                        title: "无法打开此文件：" + e.emssage,
                        mask: true,
                    });
                });
            } else if (res.cancel) { }
        }
    });
}
//文件不存在回调函数
const FileNotExistsCallback = (e, options, filename, c_url) => {
    downLoadFile(options, filename, c_url);
}
const downLoadFile = (option, filename, c_url) => {
    let i = 0;
    let updateWatting = plus.nativeUI.showWaiting("正在准备下载文件...");
    let downUrl = c_url;
    let dtask = plus.downloader.createDownload(c_url, option);
    dtask.addEventListener("statechanged", function (task, status) {
        if (!dtask) {
            return;
        }
        switch (task.state) {
            case 1: // 开始
                updateWatting.setTitle("开始下载...");
                break;
            case 2: // 已连接到服务器
                updateWatting.setTitle("链接到服务器...");
                break;
            case 3: // 已接收到数据
                updateWatting.setTitle("已下载:" + task.downloadedSize + "/" + task.totalSize);
                break;
            case 4: // 下载完成
                updateWatting.close();
                uni.showToast({
                    duration: 3500,
                    icon: 'none',
                    title: '下载完成!',
                    mask: true,
                });
                console.log('开始打开:'+option.filename);
                plus.runtime.openFile(option.filename, function (e) {
                    uni.showToast({
                        duration: 3500,
                        icon: 'none',
                        title: "无法打开此文件：" + e.emssage,
                        mask: true,
                    });
                });
                break;
        }
    });
    dtask.start();
}
const GetDownloadUrl = (file: File) => {
    let request = {
        url: LoginStore.EnjoyMain,
        data: {
            UniqueKey: "管易通40知识中心",
            MethodName: "GetDownloadUrl",
            ObjectData: {
                sUserNo: mainStore.loginInfo.sUser,
                sGuid: file.c_guid,
                sFileName: file.c_file_name
            }
        },
    };
    // console.log('入参:' + JSON.stringify(request));
    service.request(request, (res : any) => {
        // console.log('出参:' + JSON.stringify(res.data));
        if (res && res.data && !res.data.HasException) {
            UpdateDownloadCount(file.c_id);
            var url = `${LoginStore.EnjoyMain.replace('/Enjoy/Service', '/DownloadTempFile/')}${mainStore.loginInfo.sUser}` + '/' + encodeURI(file.c_file_name);
            if (plus.os.name != "iOS") {
                plus.runtime.openURL(url);
            } else {
                console.log('fileName:'+file.c_file_name)
                let options = {
                    filename: '_downloads/' + file.c_file_name,
                    method: 'GET',
                };
                plus.io.resolveLocalFileSystemURL(options.filename,
                    function (entry) {
                        FileExistsCallback(entry, options, file.c_file_name,
                            url);
                    },
                    function (e) {
                        FileNotExistsCallback(e, options, file.c_file_name,url);
                    }
                );
            }
        } else {
            service.enjoyShowToast(res.data.Exception.Message)
        }
    }, () => {
        service.enjoyHideLoading();
        console.log('失败')
    });
}
const UpdateDownloadCount = (bId: string) => {
    let request = {
        url: LoginStore.EnjoyMain,
        data: {
            UniqueKey: "管易通40知识中心",
            MethodName: "UpdateDownloadCount",
            ObjectData: bId,
            UserNo: mainStore.loginInfo.sUser
        },
    };
    service.request(request, (res : any) => {
        if (res && res.data && !res.data.HasException) {
            eventBus.emit('refresh-DocRecList');
        } else {
            service.enjoyShowToast(res.data.Exception.Message)
        }

        service.enjoyHideLoading();
    }, () => {
        service.enjoyHideLoading();
        console.log('失败')
    });
}

const handleFileAction = (file: File) => {
    switch (file.c_type) {
        case '文件':
            uni.showModal({
                title: '提示',
                content: `确定要下载文件《${file.c_title}》吗?`,
                showCancel: true,
                success: (res) => {
                    if (res.confirm) {
                        console.log('点击了确定，准备下载文件:', file);
                        GetDownloadUrl(file);
                    }
                }
            });
            break;
        case '在线编辑':
            UpdateReadCount(file.c_id);
            uni.navigateTo({
                url: '/pages/OaViews/Knowledge/KnowledgeRichText?data=' + JSON.stringify(file)
            });
            break;
        case '地址链接':
            var lk = file.c_link;
            UpdateReadCount(file.c_id);
            if (lk.substring(0, 4) == 'www.') {
                lk = 'http://' + lk;
            }
            console.log(270, lk);
            //iframe打开安全链接有安全限制，直接用浏览器打开
            if (lk.substr(0, 5) == 'https') {
                plus.runtime.openURL(lk);
            } else {
                uni.navigateTo({
                    url: '/pages/OaViews/Knowledge/KnowledgeRichText?data=' + JSON.stringify(file)
                });
            }
            break;
        default:
            console.warn('未知的文件类型:', file.c_type);
    }
}

// 更新
const UpdateReadCount = (bId: string) => {
    let request = {
        url: LoginStore.EnjoyMain,
        data: {
            UniqueKey: "管易通40知识中心",
            MethodName: "UpdateReadCount",
            ObjectData: bId,
            UserNo: mainStore.loginInfo.sUser,
        },
    };
    service.request(request, (res : any) => {
        if (res && res.data && !res.data.HasException) {
            // console.log('更新阅读计数成功, 调用刷新');
            eventBus.emit('refresh-KnowledgeList');
        } else {
            service.enjoyShowToast(res.data.Exception.Message)
        }

        service.enjoyHideLoading();
    }, () => {
        service.enjoyHideLoading();
        console.log('失败')
    });
}
</script>
  
<style lang="scss" scoped>
.item-box {
    margin-top: 28px;
    margin-bottom: 36rpx;
    height: 88rpx;
    font-family: PingFangSC, PingFang SC;
    ::v-deep .u-tag-wrapper {
        font-weight: 500;
        font-size: 20rpx;
        font-family: PingFangSC, PingFang SC;
    }
}
.left {
    position: relative;
    width: 88rpx;
    height: 88rpx;
    .point {
        position: absolute;
        top: 2px;
        right: 1px;
    }   
    .image {
        width: 100%;
        height: 100%;
    }
}
.right {
    flex: 1;
    width: 0;
    height: 88rpx;
    margin-left: 20rpx;
}
.sub_des {
    margin-right: 16rpx;    
	font-size: 24rpx;
}

::v-deep .u-tag--medium {
    padding-left: 8rpx;
    padding-right: 8rpx
}
</style>